﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Eshouse.Bll
{
    /// <summary>
    /// 主键生成方法
    /// </summary>
    public  class CRC32Primarykey
    {
         public Int32 createIntID(string ojbect_rdn)
        {


            ulong sInputUlong = StringCRC(ojbect_rdn);
            //根据给定的算法计算INT_ID
            Int32 int_ID = GetInt32CRC32(sInputUlong);
            //使用算法将字符串转换为数值
            //int_ID = this.ConvertMD5ToNumber(int_ID);
            return int_ID;
        }

        protected ulong[] crc32Table;

        /**/
        //// <summary>
        /// 构造：初始化效验表
        /// </summary>
        public CRC32Primarykey()
        {
            const ulong ulPolynomial = 0xEDB88320;
            ulong dwCrc;
            crc32Table = new ulong[256];
            int i, j;
            for (i = 0; i < 256; i++)
            {
                dwCrc = (ulong)i;
                for (j = 8; j > 0; j--)
                {
                    if ((dwCrc & 1) == 1)
                        dwCrc = (dwCrc >> 1) ^ ulPolynomial;
                    else
                        dwCrc >>= 1;
                }
                crc32Table[i] = dwCrc;
            }
        }

        /**/
        //// <summary>
        /// 字节数组效验
        /// </summary>
        /// <param name="buffer">ref 字节数组</param>
        /// <returns></returns>
        public ulong ByteCRC(ref byte[] buffer)
        {
            ulong ulCRC = 0xffffffff;
            ulong len;
            len = (ulong)buffer.Length;
            for (ulong buffptr = 0; buffptr < len; buffptr++)
            {
                ulong tabPtr = ulCRC & 0xFF;
                tabPtr = tabPtr ^ buffer[buffptr];
                ulCRC = ulCRC >> 8;
                ulCRC = ulCRC ^ crc32Table[tabPtr];
            }
            return ulCRC ^ 0xffffffff;
        }


        /**/
        //// <summary>
        /// 字符串效验
        /// </summary>
        /// <param name="sInputString">字符串</param>
        /// <returns></returns>
        public ulong StringCRC(string sInputString)
        {
            byte[] buffer = Encoding.Default.GetBytes(sInputString);
            return ByteCRC(ref buffer);
        }


        /**/
        //// <summary>
        /// 无符号数64位转换成有符号数32位
        /// </summary>
        /// <param name="sInputUlong">输入无符号数</param>
        /// <returns></returns>
        public Int32 GetInt32CRC32(ulong sInputUlong)
        {
            Int32 int32CRC32;
            if (sInputUlong > 2147483648)
            {
                int32CRC32 = Convert.ToInt32(Convert.ToUInt32(sInputUlong) - 4294967296);
            }
            else
            {
                int32CRC32 = Convert.ToInt32(sInputUlong);
            }

            return int32CRC32;
        }

    }
}
